package com.prd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.prd.dto.AttendanceVocationDTO;
import com.prd.model.AttendanceVocationDO;
import com.prd.mapper.AttendanceVocationMapper;
import com.prd.service.AttendanceVocationService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.prd.util.JsonData;
import lombok.extern.slf4j.Slf4j;
import org.flowable.bpmn.model.BpmnModel;
import org.flowable.engine.ProcessEngine;
import org.flowable.engine.ProcessEngineConfiguration;
import org.flowable.engine.RepositoryService;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.runtime.Execution;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.image.ProcessDiagramGenerator;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lizhaoyi
 * @since 2023-10-18
 */
@Service
@Slf4j
public class AttendanceVocationServiceImpl extends ServiceImpl<AttendanceVocationMapper, AttendanceVocationDO> implements AttendanceVocationService {

    @Autowired
    private AttendanceVocationMapper attendanceVocationMapper;

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private RepositoryService repositoryService;

    @Qualifier("processEngine")
    @Autowired
    private ProcessEngine processEngine;

    /**
     * 申请假期并启动工作流
     * @param attendanceVocationDTO
     * @return
     */
    @Override
    public JsonData askForVocation(AttendanceVocationDTO attendanceVocationDTO) {
        //启动工作流
        String processInstanceId = startProcess(attendanceVocationDTO);
        //save
        AttendanceVocationDO attendanceVocationDO = dto2Do(attendanceVocationDTO);
        attendanceVocationDO.setProcessId(processInstanceId);
        attendanceVocationDO.setCreatTime(LocalDateTime.now());
        attendanceVocationMapper.insert(attendanceVocationDO);

        return JsonData.buildSuccess();
    }

    /**
     * 分页查询假期记录
     * @param page
     * @param size
     * @param userId
     * @return
     */
    @Override
    public Map<String, Object> page(int page, int size, String userId) {

        Page<AttendanceVocationDO> pageInfo = new Page<>(page, size);

        IPage<AttendanceVocationDO> productDOIPage = attendanceVocationMapper.selectPage(pageInfo, new QueryWrapper<AttendanceVocationDO>().eq("applicant_id",userId));

        Map<String, Object> pageMap = new HashMap<>(3);

        pageMap.put("total_record", productDOIPage.getTotal());
        pageMap.put("total_page", productDOIPage.getPages());
        pageMap.put("data", productDOIPage.getRecords().stream().map(obj -> do2Dto(obj)).collect(Collectors.toList()));

        return pageMap;
    }

    /**
     * 查看假期申请详情
     * @param id
     * @param userId
     * @return
     */
    @Override
    public JsonData getDetail(int id, String userId) {

        QueryWrapper<AttendanceVocationDO> wrapper = new QueryWrapper<>();
        wrapper.eq("id",id);
        wrapper.eq("user_id",userId);
        AttendanceVocationDO attendanceVocationDO = attendanceVocationMapper.selectOne(wrapper);

        return JsonData.buildSuccess(attendanceVocationDO);
    }

    /**
     * 销假
     * @param attendanceVocationDTO
     * @return
     */
    @Override
    public JsonData cancelVocation(AttendanceVocationDTO attendanceVocationDTO) {

        attendanceVocationDTO.setCancelDate(LocalDate.now());
        attendanceVocationDTO.setRealVocationTime(String.valueOf(ChronoUnit.DAYS.between(LocalDate.now(), attendanceVocationDTO.getVocationDate())));

        int i = attendanceVocationMapper.updateById(dto2Do(attendanceVocationDTO));

        if (i == 0) {
            log.error("销假异常，请联系管理员");
        }else {
            return JsonData.buildSuccess();
        }

        return null;

    }

    /**
     * 查看工作流程图
     * @param resp
     * @param processId
     */
    @Override
    public void showProcessPic(HttpServletResponse resp, String processId) throws IOException {

        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(processId).singleResult();
        if (processInstance == null) {
            return;
        }
        List<Execution> executions = runtimeService
                .createExecutionQuery()
                .processInstanceId(processId)
                .list();

        List<String> activityIds = new ArrayList<>();
        List<String> flows = new ArrayList<>();
        for (Execution exe : executions) {
            List<String> ids = runtimeService.getActiveActivityIds(exe.getId());
            activityIds.addAll(ids);
        }

        /**
         * 生成流程图
         */
        BpmnModel bpmnModel = repositoryService.getBpmnModel(processInstance.getProcessDefinitionId());
        ProcessEngineConfiguration engconf = processEngine.getProcessEngineConfiguration();
        ProcessDiagramGenerator diagramGenerator = engconf.getProcessDiagramGenerator();
        InputStream in = diagramGenerator.generateDiagram(bpmnModel, "png", activityIds, flows, engconf.getActivityFontName(), engconf.getLabelFontName(), engconf.getAnnotationFontName(), engconf.getClassLoader(), 1.0, false);
        OutputStream out = null;
        byte[] buf = new byte[1024];
        int legth = 0;
        try {
            out = resp.getOutputStream();
            while ((legth = in.read(buf)) != -1) {
                out.write(buf, 0, legth);
            }
        } finally {
            if (in != null) {
                in.close();
            }
            if (out != null) {
                out.close();
            }
        }
    }


    private String startProcess(AttendanceVocationDTO attendanceVocationDTO) {
        HashMap<String, Object> map = new HashMap<>(3);
        map.put("zuzhangTask", attendanceVocationDTO.getApproveName());
        // 开启流程的key，就是流程定义文件里 process 标签的id
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("ask_for_vocation", map);
        // 设置一些参数
        runtimeService.setVariable(processInstance.getId(), "name", attendanceVocationDTO.getApplicantName());
        runtimeService.setVariable(processInstance.getId(), "reason", attendanceVocationDTO.getTitle());
        runtimeService.setVariable(processInstance.getId(), "date", attendanceVocationDTO.getVocationDate());
        log.info("创建外勤流程 processId：{}", processInstance.getId());
        return processInstance.getId();
    }

    private AttendanceVocationDO dto2Do(AttendanceVocationDTO attendanceVocationDTO) {
        AttendanceVocationDO attendanceVocationDO = new AttendanceVocationDO();
        BeanUtils.copyProperties(attendanceVocationDTO, attendanceVocationDO);
        return attendanceVocationDO;
    }

    private AttendanceVocationDTO do2Dto(AttendanceVocationDO attendanceVocationDO) {
        AttendanceVocationDTO attendanceVocationDTO = new AttendanceVocationDTO();
        BeanUtils.copyProperties(attendanceVocationDO, attendanceVocationDTO);
        return attendanceVocationDTO;
    }
}
